import Axios from 'axios';
import adapter from './adapter';
import store from '../store';
import { checkParamsIsSafe } from '../utils';

console.log('store', store);

export const BASE_URL = ''

const instance = Axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  adapter: adapter
})

const checkParamSafe = (config) => {
  let result = true;
  const { method, data, params } = config
  if (['get', 'GET'].includes(method)) {
    const isSafe = checkParamsIsSafe(params)
    result = isSafe
  }
  if (['post', 'POST'].includes(method)) {
    const isSafe = checkParamsIsSafe(data)
    result = isSafe
  }
  return result
}

// 请求拦截器
instance.interceptors.request.use((config) => {
  if (!checkParamSafe(config)) {
    uni.showToast({ title: '参数存在非法字符，请重新输入', icon: 'none' })
    return;
  }
  uni.showLoading({ title: '加载中...' })
  config.headers = {
    'Authorization': `Bearer`
  }
  return config
}, (error) => {
  console.log('request error>>>>>', error);
  uni.hideLoading()
  return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use((response) => {
  uni.hideLoading()
  return response.data
}, (error) => {
  console.log('response error>>>>>', error);
  uni.hideLoading()
  return Promise.reject(error)
})

/**
* get方法，对应get请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function $get(url, params) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, { params })
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}

/**
* post方法，对应post请求
* @param {*} url
* @param {*} params
* @returns
*/
export function $post(url, params) {
  return new Promise((resolve, reject) => {
    instance
      .post(url, params)
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}
